package org.tao.lightningmq.broker.slave;

import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tao.lightningmq.common.dto.StartSyncReqDTO;
import org.tao.lightningmq.common.dto.StartSyncRespDTO;
import org.tao.lightningmq.common.enums.BrokerEventCode;
import org.tao.lightningmq.common.event.EventBus;
import org.tao.lightningmq.common.remote.BrokerNettyRemoteClient;
import org.tao.lightningmq.common.tcp.TcpMsg;

import java.util.UUID;

/**
 * @Author lht
 * @date 2025/1/21 - 14:12
 * @description: 从节点同步服务
 */
public class SlaveSyncService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SlaveSyncService.class);
    private BrokerNettyRemoteClient brokerNettyRemoteClient;

    private String currentMasterAddr;

    public boolean connectMasterBrokerNode(String address) {
        this.currentMasterAddr = address;
        String addressAddr[] = address.split(":");
        String ip = addressAddr[0];
        Integer port = Integer.valueOf(addressAddr[1]);
        try {
            brokerNettyRemoteClient = new BrokerNettyRemoteClient(ip, port);
            brokerNettyRemoteClient.buildConnection(new SlaveSyncServerHandler(new EventBus("slave-sync-eventbus")));
            return true;
        } catch (Exception e) {
            LOGGER.error("error connect master broker", e);
        }
        return false;
    }

    public void sendStartSyncMsg() {
        StartSyncReqDTO startSyncReqDTO = new StartSyncReqDTO();
        startSyncReqDTO.setMsgId(UUID.randomUUID().toString());
        TcpMsg tcpMsg = new TcpMsg(BrokerEventCode.START_SYNC_MSG.getCode(), JSON.toJSONBytes(startSyncReqDTO));
        TcpMsg resp = brokerNettyRemoteClient.sendSyncMsg(tcpMsg, startSyncReqDTO.getMsgId());
        LOGGER.info("startSyncMsgResp is:{}", JSON.toJSONString(resp));
    }

    public void closeConnection() {
        if (this.brokerNettyRemoteClient.isChannelActive())
            this.brokerNettyRemoteClient.close();
    }

    public String getCurrentMasterAddr() {
        return currentMasterAddr;
    }
}
